package com.md.livingwidget.toast;

import android.app.Dialog;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieDrawable;
import com.md.basedpc.PHUtils;
import com.md.livingwidget.R;

/**
 * create by 徐黎平 on 2020年03月10日13:28:17
 * 加载窗控件
 */
public class PHLoading extends Dialog {

    /**
     * 提示文字
     */
    private TextView mTextView;
    private LottieAnimationView lottieAnimationView;
    /**
     * 0 不可取消 1 返回键可取消 2 点哪都能取消
     */
    private int cancelType = 0;

    public PHLoading(Context context, String msg, int cancelType) {
        //使用自定义的Style
        super(context, R.style.LoadingDialog);
        //使用自定义的layout
        setContentView(R.layout.ph_dialog_loading);
        mTextView = findViewById(R.id.loading_msg);
        lottieAnimationView = findViewById(R.id.ph_loading_process_dialog);
        lottieAnimationView.setAnimation("lottie_json/ph_loading.json");
        lottieAnimationView.setRepeatCount(LottieDrawable.INFINITE);
        setText(msg);
        this.cancelType = cancelType;
        setCancelable(cancelType != 0);
    }

    public void setText(String s) {
        if (mTextView != null) {
            if (!PHUtils.isEmpty(s)) {
                mTextView.setText(s);
                mTextView.setVisibility(View.VISIBLE);
            } else {
                mTextView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            return cancelType == 1;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (lottieAnimationView != null) {
            lottieAnimationView.setProgress(0);
            lottieAnimationView.playAnimation();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (lottieAnimationView != null) {
            lottieAnimationView.cancelAnimation();
        }
    }
}
